<?php
declare(strict_types=1);

namespace app\controller\user;

use app\controller\BaseController;
use app\model\UserAddress;
use app\validate\UserAddressValidate;
use think\exception\ValidateException;

class UserAddressController extends BaseController
{
    /**
     * 地址列表
     * @return \think\response\Json
     */
    public function list()
    {
        $user = $this->request->user;
        $type = $this->request->get('type', 0); // 0全部 1寄件地址 2收件地址

        $where = ['user_id' => $user->id];
        if ($type) {
            $where['address_type'] = $type;
        }

        $list = UserAddress::where($where)
            ->order('id', 'desc')
            ->select();

        return $this->success([
            'list' => $list
        ]);
    }

    /**
     * 保存地址
     */
    public function save()
    {
        $params = $this->request->post();
        $user = $this->request->user;

        try {
            validate(UserAddressValidate::class)
                ->scene('save')
                ->check($params);

            $data = [
                'user_id' => $user->id,
                'merchant_id' => $user->merchant_id,
                'address_type' => $params['address_type'],
                'province' => $params['province'],
                'city' => $params['city'],
                'county' => $params['county'],
                'address' => $params['address'],
                'username' => $params['username'],
                'phone' => $params['phone']
            ];

            if (!empty($params['id'])) {
                // 更新地址
                $address = UserAddress::where([
                    'id' => $params['id'],
                    'user_id' => $user->id
                ])->find();

                if (!$address) {
                    return $this->error('地址不存在');
                }

                $address->save($data);
            } else {
                // 创建地址
                UserAddress::create($data);
            }

            return $this->success();

        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除地址
     */
    public function delete($id)
    {
        $user = $this->request->user;

        $address = UserAddress::where([
            'id' => $id,
            'user_id' => $user->id
        ])->find();

        if (!$address) {
            return $this->error('地址不存在');
        }

        $address->delete();

        return $this->success();
    }
} 